<template>
  <div class="userList">
    <div class="title">
      用户列表
    </div>
    <!-- 顶部搜索 -->
    <div class="header-top">
      <el-form :inline="true">
        <el-form-item>
          <el-input clearable v-model="tiaojian.text" placeholder="用户名或手机号" style="width: 200px;"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button class="search" type="primary" @click="goSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 列表 -->
    <el-table :data="initData.list" style="width: 100%" max-height="450" v-loading="loading">
      <el-table-column align="center" header-align="center" prop="avatar" label="头像" width="100">
        <template slot-scope="scope">
          <img :src="initData.url + scope.row.avatar" width="80" height="100">
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="userName" label="用户昵称">
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="email" label="邮箱" width="150">
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="phone" label="手机号" width="120">
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="sex" label="性别">
        <template slot-scope="scope">
          {{((key)=>{
            switch(key){
              case 0: return '男';break;
              case 1: return '女';break;
              default: return '未知';break;
            }
          })(scope.row.sex)}}
        </template>
      </el-table-column>

      <el-table-column align="center" header-align="center" prop="createdAt" label="注册日期" width="160" sortable>
        <template slot-scope="scope">
          {{$util.formDate(scope.row.createdAt)}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" prop="updatedAt" label="更新日期" width="160" sortable>
        <template slot-scope="scope">
          {{$util.formDate(scope.row.updatedAt)}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="实名状态">
        <template slot-scope="scope">
          {{(()=>{
            if(scope.row.realName != '' && scope.row.idCardNo != ''){
              return '已实名';
            }else{
              return '未实名';
            }
          })(scope.row.realName, scope.row.idCardNo)}}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="warning" size="mini" @click="editInfo(scope.row)">编辑</el-button>
          <!-- <el-button type="danger" size="mini">删除</el-button> -->
          <el-popconfirm title="确定删除此用户吗？" @confirm="delRecord(scope.row)" style="margin-left:10px">
            <el-button size="mini" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.page" :page-sizes="[10, 15, 20]" :page-size="params.size" layout="total, sizes, prev, pager, next, jumper" :total="params.total"></el-pagination>

    <!-- 编辑对话框 -->
    <el-dialog :visible.sync="dialog.edit" width="650px" center>
      <template slot="title">
        <b>编辑用户</b>
      </template>
      <el-form ref="infoData" :model="infoData" label-width="90px" :inline="true" :rules="rules">
        <el-form-item label="用户昵称" prop="userName">
          <el-input v-model="infoData.userName" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="infoData.phone" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="infoData.email" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="infoData.password" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="infoData.realName" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="idCardNo">
          <el-input v-model="infoData.idCardNo" style="width:200px;"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="infoData.sex" style="width:200px;">
            <el-radio-button label="1">男</el-radio-button>
            <el-radio-button label="0">女</el-radio-button>
            <el-radio-button label="2">未知</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="头像">
          <img :src="initData.url + infoData.avatar" alt="" width="80" height="100">
        </el-form-item>

        <div style="text-align: center;">
          <el-button @click="dialog.edit = false" style="width: 100px">取消</el-button>
          <el-button type="primary" @click="submit" style="width: 100px">确定</el-button>
        </div>

      </el-form>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'userList',
  data() {
    return {
      loading: false,
      initData: {
        list: [],
        url: '',
      },
      dialog: {
        edit: false,
      },
      infoData: {
        id: '',
        userName: '',
        phone: '',
        password: '',
        email: '',
        realName: '',
        idCardNo: '',
        sex: '',
        avatar: '',
      },
      rules: {
        userName: [{ validator: this.validUsername, trigger: "blur" }],
        realName: [{ validator: this.validRealname, trigger: "blur" }],
        idCardNo: [{ validator: this.validIdCardNo, trigger: "blur" }],
        password: [{ validator: this.validPw, trigger: "blur" }],
        email: [{ validator: this.validateEmail, trigger: "blur" },],
        phone: [{ validator: this.validatePhone, trigger: "blur" },],
      },
      tiaojian:{
        text: '',
      },
      params: {
        page: 1,
        size: 10,
        total: 0,
        text: '',
      },
    }
  },
  created() {
    if(this.$cookies.get('__ac') != 1){
      this.$router.push({name: 'B_HouseList'})
      return
    }
    let oj = {
      title: '用户列表',
      nav: '2-1',
    };
    this.$emit('isTitle', oj);
    this.init();
  },
  methods: {
    init() {
      this.loading = true;
      let data = {
        page: this.params.page,
        size: this.params.size,
        text: this.params.text,
      }
      this.axios({
        method: 'get',
        url: this.baseUrl + '/getUserlist',
        params: data
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          this.loading = false;
          this.initData.list = res.data.data;
          this.initData.url = res.data.url;
          this.params.total = res.data.total;
          console.log(this.initData.list)
          // this.$message.success(res.data.msg)
        } else {
          this.$message.error(res.data.msg)
          this.loading = false;
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    },
    // 改变搜索条件
    goSearch() {
      this.params.page = 1;
      this.params.text = this.tiaojian.text;
      this.init();
    },
    // 编辑信息
    editInfo(o) {
      if (this.$refs.infoData) {
        this.$refs.infoData.resetFields();
      }
      // console.log(o)
      this.infoData = {
        id: o.id,
        userName: o.userName,
        phone: o.phone,
        password: o.password,
        email: o.email,
        realName: o.realName,
        idCardNo: o.idCardNo,
        sex: o.sex,
        avatar: o.avatar,
      };
      this.dialog.edit = true;
    },
    // 提交信息
    submit() {
      this.$refs['infoData'].validate((valid) => {
        if (valid) {
          if (this.infoData.idCardNo == '' && this.infoData.realName != '') {
            this.$message.warning('请输入身份证号!')
            return;
          } else if (this.infoData.idCardNo != '' && this.infoData.realName == '') {
            this.$message.warning('请输入真实姓名!')
            return;
          } else if (this.infoData.idCardNo != '' && this.infoData.realName != '') {
            if (this.infoData.idCardNo.charAt(this.infoData.idCardNo.length - 2) % 2 == this.infoData.sex) {
              this.$message.warning('身份证号与性别不符')
              return;
            }
          }
          // 发起请求
          this.axios({
            method: 'post',
            url: this.baseUrl + '/editUser',
            data: this.infoData
          }).then(res => {
            console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.dialog.edit = false;
              this.params.page = 1;
              this.init();
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(err => {
            console.log('err==>', err)
            this.$message.error(res.data.msg)
          })
        } else {
          this.$message.warning('请完善所有信息')
        }
      })

    },
    // 删除用户
    delRecord(o) {
      this.axios({
        method: 'post',
        url: this.baseUrl + '/deleteUser',
        data: {
          id: o.id,
        }
      }).then(res => {
        console.log('res==>', res)
        if (res.data.code == 200) {
          this.$message.success('删除用户成功')
          this.params.page = 1;
          this.init();
        } else {
          this.$message.error('删除用户失败')
        }
      }).catch(err => {
        console.log('err==>', err)
        this.$message.error(res.data.msg)
      })
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params.size = val;
      this.init();
    },
    // 当前页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
      this.init();
    },


    // -----------------------------验证-----------------------------------
    // 验证网站昵称
    validUsername(rule, value, callback) {
      if (value == '') {
        callback(Error("请输入用户昵称"));
      } else {
        callback();
      }
    },
    // 验证真实姓名
    validRealname(rule, value, callback) {
      if (!value) {
        // callback(new Error("姓名不能为空"));
        callback();
      } else if (!/^[\u4e00-\u9fa5·]{2,5}/.test(value)) {
        callback(new Error("姓名有误!"));
      } else {
        callback();
      }
    },
    // 验证身份证
    validIdCardNo(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        let reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
        if (!reg.test(value)) {
          callback(new Error("身份证有误!"));
        } else {
          callback();
        }
      }
    },
    // 验证密码(首字符为字母, 字母数字_组合, 6-16位)
    validPw(rule, value, callback) {
      if (!value) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    },
    // 邮箱验证
    validateEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入邮箱'));
      } else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
        callback(new Error('邮箱格式不正确'));
      } else {
        callback();
      }
    },
    // 手机号验证
    validatePhone(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      } else {
        callback();
      }
    },
  }
}
</script>

<style lang="less" scoped>
.userList {
  background-color: #fff;
  .title {
    font-size: 20px;
    height: 40px;
    line-height: 40px;
    margin-bottom: 20px;
    font-weight: bold;
  }
  .el-pagination {
    margin-top: 30px;
    text-align: center;
  }
}
</style>